/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-07-07     17247       the first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "uart_protocol.h"
#include "uart5.h"
#include "sht31_thread.h"

static void uart5_send_time_thread_entry(void *parameter);
// 事件/异常标志位（需在协议解析层设置和清零）
volatile int bed_status_changed = 0;
volatile int sleep_quality_score_flag = 0;
volatile int sleep_analysis_flag = 0;
volatile int sleep_rating_flag = 0;
volatile int sleep_abnormal_flag = 0;
volatile int struggle_abnormal_flag = 0;

// 实时数据上报（心率、呼吸、人体存在、体动、温湿度3秒一发）
static void send_realtime_json(int tick)
{
    if (tick % 3 == 0) {
        char json_buf[192];
        float temp = get_global_temperature();
        float humi = get_global_humidity();
        
        // Handle NaN values
        if (isnan(temp) || isnan(humi)) {
            return; // Skip sending if sensor data is invalid
        }
        
        // Convert float to integer for JSON (avoid %f issues)
        int temp_int = (int)(temp * 10);
        int humi_int = (int)(humi * 10);
        
        rt_snprintf(json_buf, sizeof(json_buf),
            "{\"type\":\"realtime\",\"exist_info\":%d,\"heart_rate\":%d,\"breathing\":%d,\"body_movement\":%d,\"temperature\":%d.%d,\"humidity\":%d.%d}",
            global_exist_info,
            global_heart_rate_value,
            global_breathing_value,
            global_body_movement,
            temp_int / 10, temp_int % 10,
            humi_int / 10, humi_int % 10
        );
        uart5_send(json_buf, rt_strlen(json_buf));
    }
}

// 周期性睡眠数据上报
static void send_periodic_sleep_json(void)
{
    char json_buf[256];
    rt_snprintf(json_buf, sizeof(json_buf),
        "{\"type\":\"periodic\",\"sleep_status\":%d,\"awake_duration\":%d,\"light_sleep_duration\":%d,\"deep_sleep_duration\":%d,\"sleep_comprehensive\":[%d,%d,%d,%d,%d,%d,%d,%d]}",
        global_sleep_status,
        global_awake_duration,
        global_light_sleep_duration,
        global_deep_sleep_duration,
        global_sleep_comprehensive_data[0], global_sleep_comprehensive_data[1], global_sleep_comprehensive_data[2], global_sleep_comprehensive_data[3],
        global_sleep_comprehensive_data[4], global_sleep_comprehensive_data[5], global_sleep_comprehensive_data[6], global_sleep_comprehensive_data[7]
    );
    uart5_send(json_buf, rt_strlen(json_buf));
}

// 事件/异常即时上报
static void send_bed_status_json(void)
{
    char json_buf[64];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"bed_status\",\"bed_status\":%d}", global_bed_status);
    uart5_send(json_buf, rt_strlen(json_buf));
}
static void send_sleep_quality_score_json(void)
{
    char json_buf[64];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"sleep_quality_score\",\"score\":%d}", global_sleep_quality_score);
    uart5_send(json_buf, rt_strlen(json_buf));
}
static void send_sleep_analysis_json(void)
{
    char json_buf[128];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"sleep_analysis\",\"data\":[%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d]}",
        global_sleep_analysis_data[0], global_sleep_analysis_data[1], global_sleep_analysis_data[2], global_sleep_analysis_data[3],
        global_sleep_analysis_data[4], global_sleep_analysis_data[5], global_sleep_analysis_data[6], global_sleep_analysis_data[7],
        global_sleep_analysis_data[8], global_sleep_analysis_data[9], global_sleep_analysis_data[10], global_sleep_analysis_data[11]);
    uart5_send(json_buf, rt_strlen(json_buf));
}
static void send_sleep_rating_json(void)
{
    char json_buf[64];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"sleep_rating\",\"rating\":%d}", global_sleep_quality_score); // 假设rating同score
    uart5_send(json_buf, rt_strlen(json_buf));
}
static void send_sleep_abnormal_json(void)
{
    char json_buf[64];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"sleep_abnormal\"}");
    uart5_send(json_buf, rt_strlen(json_buf));
}
static void send_struggle_abnormal_json(void)
{
    char json_buf[64];
    rt_snprintf(json_buf, sizeof(json_buf), "{\"type\":\"event\",\"event\":\"struggle_abnormal\"}");
    uart5_send(json_buf, rt_strlen(json_buf));
}

int uart5_send_time_thread_init(void)
{
    rt_kprintf("[uart5_send_time] Initializing periodic send thread...\n");
    rt_thread_t tid = rt_thread_create("uart5_json", uart5_send_time_thread_entry, RT_NULL, 1024, 20, 10);
    if (tid)
    {
        rt_kprintf("[uart5_send_time] Thread created, starting...\n");
        rt_thread_startup(tid);
        rt_kprintf("[uart5_send_time] Thread started!\n");
    }
    else
    {
        rt_kprintf("[uart5_send_time] Thread creation failed!\n");
    }
    return RT_EOK;
}

static void uart5_send_time_thread_entry(void *parameter)
{
    rt_kprintf("[uart5_send_time] Thread entry running, periodic report started...\n");
    int report_counter = 0;
    int tick = 0;
    while (1)
    {
        send_realtime_json(tick);
        if (++report_counter >= 600) { // 10min
            send_periodic_sleep_json();
            report_counter = 0;
        }
        // 特殊事件即时上报，事件标志位需在协议解析处设置
        if (bed_status_changed) {
            send_bed_status_json();
            bed_status_changed = 0;
        }
        if (sleep_quality_score_flag) {
            send_sleep_quality_score_json();
            sleep_quality_score_flag = 0;
        }
        if (sleep_analysis_flag) {
            send_sleep_analysis_json();
            sleep_analysis_flag = 0;
        }
        if (sleep_rating_flag) {
            send_sleep_rating_json();
            sleep_rating_flag = 0;
        }
        if (sleep_abnormal_flag) {
            send_sleep_abnormal_json();
            sleep_abnormal_flag = 0;
        }
        if (struggle_abnormal_flag) {
            send_struggle_abnormal_json();
            struggle_abnormal_flag = 0;
        }
        tick++;
        rt_thread_mdelay(1000);
    }
}

/* 使用应用级自初始化机制 */
INIT_APP_EXPORT(uart5_send_time_thread_init);
